// 引入store，用于管理socket推送来的消息
import store from "@/store";
let Snowflake = (function () {
  function Snowflake(_workerId, _dataCenterId, _sequence) {
    this.twepoch = 1288834974657n;
    //this.twepoch = 0n;
    this.workerIdBits = 5n;
    this.dataCenterIdBits = 5n;
    this.maxWrokerId = -1n ^ (-1n << this.workerIdBits); // 值为：31
    this.maxDataCenterId = -1n ^ (-1n << this.dataCenterIdBits); // 值为：31
    this.sequenceBits = 12n;
    this.workerIdShift = this.sequenceBits; // 值为：12
    this.dataCenterIdShift = this.sequenceBits + this.workerIdBits; // 值为：17
    this.timestampLeftShift =
      this.sequenceBits + this.workerIdBits + this.dataCenterIdBits; // 值为：22
    this.sequenceMask = -1n ^ (-1n << this.sequenceBits); // 值为：4095
    this.lastTimestamp = -1n;
    //设置默认值,从环境变量取
    this.workerId = 1n;
    this.dataCenterId = 1n;
    this.sequence = 0n;
    if (this.workerId > this.maxWrokerId || this.workerId < 0) {
      throw new Error(
        "_workerId must max than 0 and small than maxWrokerId-[" +
          this.maxWrokerId +
          "]"
      );
    }
    if (this.dataCenterId > this.maxDataCenterId || this.dataCenterId < 0) {
      throw new Error(
        "_dataCenterId must max than 0 and small than maxDataCenterId-[" +
          this.maxDataCenterId +
          "]"
      );
    }

    this.workerId = BigInt(_workerId);
    this.dataCenterId = BigInt(_dataCenterId);
    this.sequence = BigInt(_sequence);
  }
  Snowflake.prototype.tilNextMillis = function (lastTimestamp) {
    var timestamp = this.timeGen();
    while (timestamp <= lastTimestamp) {
      timestamp = this.timeGen();
    }
    return BigInt(timestamp);
  };
  Snowflake.prototype.timeGen = function () {
    return BigInt(Date.now());
  };
  Snowflake.prototype.nextId = function () {
    var timestamp = this.timeGen();
    if (timestamp < this.lastTimestamp) {
      throw new Error(
        "Clock moved backwards. Refusing to generate id for " +
          (this.lastTimestamp - timestamp)
      );
    }
    if (this.lastTimestamp === timestamp) {
      this.sequence = (this.sequence + 1n) & this.sequenceMask;
      if (this.sequence === 0n) {
        timestamp = this.tilNextMillis(this.lastTimestamp);
      }
    } else {
      this.sequence = 0n;
    }
    this.lastTimestamp = timestamp;
    return (
      ((timestamp - this.twepoch) << this.timestampLeftShift) |
      (this.dataCenterId << this.dataCenterIdShift) |
      (this.workerId << this.workerIdShift) |
      this.sequence
    );
  };
  return Snowflake;
})();
import { getToken } from "@/utils/auth.js";
let token = getToken();
let userId = store.getters.userId;
// console.log(token, "这是token");
const Ws = {
  $ws: null, // webscoket实例
  wsUrl: `ws://192.168.3.48:7002/${token}?id=${userId}`, // websocket链接地址
  // wsUrl: `ws://47.106.222.181:8889/${token}?id=${userId}`, // websocket线上地址
  timer: -1,
  tempSnowflake: new Snowflake(1n, 1n, 0n),

  // 初始化webSocket
  createWS: function () {
    if ("WebSocket" in window) {
      // //ws地址+token+?+id  token判断登录，id判断和token是否一致
      this.$ws = new WebSocket(wsUrl);
      this.$ws.onopen = this.wsOpen;
      this.$ws.onmessage = this.wsMessage;
      this.$ws.onerror = this.wsError;
      this.$ws.onclose = this.wsClose;
    } else {
      alert("Current browser Not support websocket");
    }
  },

  //连接成功建立后响应
  wsOpen: function () {
    //115秒发送一次心跳
    timer = setInterval(function () {
      var data = { type: "0" };
      this.$ws.send(JSON.stringify(data));
    }, 1000 * 115);
  },
  //收到服务器消息后响应
  wsMessage: function (e) {
    var msg = document.getElementById("msg").innerHTML;
    let data = JSON.parse(e.data);
    if (data.type == "1") {
      //消息
      console.log(data);
    } else if (data.data.type == "2") {
      // 图片和文件
    } else if (data.type == "2") {
      //本人发送的消息，其他人的已读状态
    } else if (data.type == "3") {
      //消息撤回
    }
    //服务端发送来的消息存到vuex
    store.commit("web_socket_msg", msg);
  },

  //连接关闭后响应
  wsClose: function (event) {
    console.log("== websocket close ==", event);
    window.clearInterval(timer);
    timer = -1;
  },
  // 发送消息
  sendMsg() {
    //  做判断防止发送空格
    if (!this.content) {
      return;
    }
    var time = new Date();
    console.log(this.myUrl);
    // this.chatMessages.push({
    //   myUrl: this.myUrl,
    //   msgUserid: this.userId,
    //   createTime: time,
    //   createBy: this.userId,
    //   msg: this.content,
    // });
    //type 0 心跳（120秒没有读写操作会关闭通道，要写个定时器定时发送心跳） 1 发送消息 2 消息已读 3 消息撤回
    let data = {
      type: "1",
      no: this.currentChat.orderNo,
      msg: this.content,
      msgid: this.tempSnowflake.nextId() + "",
      createBy: this.userId,
      msgUserid: this.userId,
      createTime: time,
      myUrl: this.myUrl,
    }; //no 订单号 msg 消息本体 msgid 生成的雪花算法id
    console.log(this.currentChat.orderNo);
    // var data = { "type": "2", "no": "123456", "msgid": "123456789", "msgUserid": "1" }//no 订单号  消息id msgUserid 发送该消息的用户id
    // var data = { "type": "3", "no": "123456", "msgid": "123456789" }//no 订单号 msgid 消息id
    this.ws.send(JSON.stringify(data));
    // localStorage.setItem("orderNo", this.chatMessages);
    // 清空输入框
    console.log("我是输入框");
    this.content = "";
  },
};
export default Ws;
